package service.impl;

import html.HtmlBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import listener.Listener;
import listener.ServerListener;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import service.Service;

public class WebServiceImpl extends Thread implements Service{
	
	private final static Logger logger = LogManager.getLogger(WebServiceImpl.class);
	
	private Socket socket;
	private InputStream inputStream;
	private OutputStream outputStream;
	private Listener listener;
	
	public WebServiceImpl(Socket socket){
		this.socket = socket;
		try {
			outputStream = socket.getOutputStream();
			inputStream = socket.getInputStream();
		} catch (IOException e) {
			logger.error(e);
		}
		
	}
	
	public void service(){
		BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
		try {
			String line=null;
			StringBuilder builder = new StringBuilder();
			while((line=reader.readLine()).trim().length()!=0){
				builder.append(line);
			}
			String header = builder.toString().split(" ")[1];
			if (header.equals("/?option=start")) {
				listener.listen(ServerListener.START);
			}
			if (header.equals("/?option=stop")) {
				listener.listen(ServerListener.SHUTDOWM);
			}
			Element root = new HtmlBuilder().buildHtml();
			XMLOutputter ot1=new XMLOutputter();
			outputStream.write("HTTP/1.1 200 OK\r\n\r\n".getBytes());
			ot1.output(root, outputStream);
			
		} catch (IOException e) {
			logger.error(e);
		}finally{
			try {
				outputStream.close();
				reader.close();
				socket.close();
			} catch (IOException e) {
				logger.warn(e);
			}
			
		}
		
	}

	public void setListener(Listener listener) {
		this.listener = listener;
	}

	@Override
	public void run(){
		service();
	}

	@Override
	public void close() {
		
	}
	

}
